<template>
	<a-row>
		<a-col :span="5">
			<s-tree
				class="cardImp"
				placeholder="Search"
				:loading="cardLoading"
				:expandedKeys="defaultExpandedKeys"
				:data="treeData"
				:fieldNames="treeFieldNames"
				@select="treeSelect"
			></s-tree>
		</a-col>
		<a-col :span="19">
			<a-card :bordered="false" style="margin-bottom: 10px">
				<a-form ref="searchFormRef" name="advanced_search" class="ant-advanced-search-form" :model="searchFormState">
					<a-row :gutter="24">
						<a-col :span="6">
							<a-form-item name="searchKey">
								<a-input
									v-model:value="searchFormState.searchKey"
									placeholder="请输入姓名或账号"
									@keyup.enter="table.refresh(true)"
								></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item name="userStatus">
								<a-select v-model:value="searchFormState.userStatus" placeholder="请选择状态">
									<a-select-option v-for="item in statusData" :key="item.value" :value="item.value"
										>{{ item.label }}
									</a-select-option>
								</a-select>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-button type="primary" @click="table.refresh(true)">{{ $t('common.searchButton') }} </a-button>
							<a-button class="buttom-left" @click="() => searchFormRef.resetFields()"
								>{{ $t('common.resetButton') }}
							</a-button>
						</a-col>
					</a-row>
				</a-form>
			</a-card>
			<a-card :bordered="false">
				<s-table
					ref="table"
					table-id="SYS_USER_TABLE"
					:columns="columns"
					:data="loadData"
					:expand-row-by-click="true"
					bordered
					:alert="options.alert.show"
					:row-key="(record) => record.id"
					:row-selection="options.rowSelection"
					:tool-config="toolConfig"
				>
					<template #operator>
						<a-space>
							<a-button type="primary" @click="formRef.onOpen(null, searchFormState.orgId)">
								<template #icon>
									<plus-outlined />
								</template>
								<span>{{ $t('common.addButton') }}{{ $t('model.user') }}</span>
							</a-button>
							<batch-delete
								title="确定要删除选中用户吗?"
								buttonName="删除用户"
								:selectedRowKeys="selectedRowKeys"
								@batchDelete="removeBatchUser"
							/>
							<a-button @click="openImport">
								<template #icon>
									<download-outlined />
								</template>
								导入用户
							</a-button>
							<data-export buttonName="导出用户" @dataExport="dataExportUser" />
						</a-space>
					</template>
					<template #bodyCell="{ column, record }">
						<template v-if="column?.dataIndex === 'avatar'">
							<a-avatar :src="record.avatar" style="margin-bottom: -5px; margin-top: -5px" />
						</template>
						<template v-if="column?.dataIndex === 'gender'">
							{{ $TOOL.dictTypeData('GENDER', record.gender) }}
						</template>
						<template v-if="column?.dataIndex === 'userStatus'">
							<a-switch :loading="loading" :checked="record.userStatus === 'ENABLE'" @change="editStatus(record)" />
						</template>
						<template v-if="column?.dataIndex === 'action'">
							<a @click="formRef.onOpen(record)">{{ $t('common.editButton') }}</a>
							<a-popconfirm title="确定要删除此用户吗？" @confirm="removeUser(record)">
								<a-button type="link" danger size="small">{{ $t('common.removeButton') }}</a-button>
							</a-popconfirm>
							<!-- <a-divider type="vertical" /> -->
							<a-dropdown>
								<a class="ant-dropdown-link">
									更多
									<DownOutlined />
								</a>
								<template #overlay>
									<a-menu>
										<a-menu-item>
											<a-popconfirm title="确定重置此用户密码？" placement="topRight" @confirm="resetPassword(record)">
												<a>重置密码</a>
											</a-popconfirm>
										</a-menu-item>
										<a-menu-item>
											<a @click="selectRole(record)">授权角色</a>
										</a-menu-item>
										<a-menu-item>
											<a @click="grantResourceRef.onOpen(record)">授权资源</a>
										</a-menu-item>
										<a-menu-item>
											<a @click="grantPermissionRef.onOpen(record)">授权权限</a>
										</a-menu-item>
									</a-menu>
								</template>
							</a-dropdown>
						</template>
					</template>
				</s-table>
			</a-card>
		</a-col>
	</a-row>
	<grantResourceForm ref="grantResourceRef" :api="userApi" :if-user="true" @successful="table.refresh()" />
	<grantPermissionForm ref="grantPermissionRef" :api="userApi" @successful="table.refresh()" />
	<Form ref="formRef" @successful="table.refresh()" />
	<role-selector-plus
		ref="RoleSelectorPlusRef"
		:org-tree-api="selectorApiFunction.orgTreeApi"
		:role-page-api="selectorApiFunction.rolePageApi"
		:checked-role-list-api="selectorApiFunction.checkedRoleListApi"
		@onBack="roleBack"
	/>
	<data-import
		ref="importRef"
		title="导入用户"
		:api="userApi"
		:max-upload-count="2000"
		@successful="table.refresh(true)"
	/>
</template>

<script setup name="sysUser">
	import userApi from '@/api/sys/userApi'
	import userCenterApi from '@/api/sys/userCenterApi'
	import Form from './form.vue'
	import tool from '@/utils/tool'
	import RoleSelectorPlus from '@/components/Selector/roleSelectorPlus.vue'
	import GrantResourceForm from '../role/grantResourceForm.vue'
	import GrantPermissionForm from '../role/grantPermissionForm.vue'
	import { isEmpty } from 'lodash-es'

	const toolConfig = { refresh: true, height: true, columnSetting: true, striped: false } //表格工具配置
	const columns = [
		{
			title: '头像',
			dataIndex: 'avatar',
			align: 'center',
			width: '80px'
		},
		{
			title: '账号',
			dataIndex: 'account',
			ellipsis: true
		},
		{
			title: '姓名',
			dataIndex: 'name'
		},
		{
			title: '性别',
			dataIndex: 'gender',
			width: '50px'
		},
		{
			title: '手机',
			dataIndex: 'phone',
			ellipsis: true
		},
		{
			title: '机构',
			dataIndex: 'orgName',
			ellipsis: true
		},
		{
			title: '职位',
			dataIndex: 'positionName',
			ellipsis: true
		},
		{
			title: '状态',
			dataIndex: 'userStatus',
			width: '80px'
		},
		{
			title: '操作',
			dataIndex: 'action',
			align: 'center',
			width: '150px'
		}
	]
	const statusData = tool.dictList('COMMON_STATUS')
	const importRef = ref() //导入组件
	const searchFormRef = ref() //搜索
	const defaultExpandedKeys = ref([])
	const searchFormState = ref({})
	const table = ref(null) //表格
	const treeData = ref([]) //树结构数据
	const selectedRowKeys = ref([]) //选择项
	const treeFieldNames = { children: 'children', title: 'name', key: 'id' }
	const formRef = ref(null) //表单
	const RoleSelectorPlusRef = ref() //角色选择器
	const selectedRecord = ref({}) //角色选择记录
	const loading = ref(false) //加载中
	const cardLoading = ref(true) //卡片加载中
	const grantResourceRef = ref()
	const grantPermissionRef = ref()
	// 表格查询 返回 Promise 对象
	const loadData = (parameter) => {
		return userApi.userPage(Object.assign(parameter, searchFormState.value)).then((res) => {
			return res
		})
	}
	// 左侧树查询
	userApi.userOrgTreeSelector().then((res) => {
		cardLoading.value = false
		if (res !== null) {
			treeData.value = res
			if (isEmpty(defaultExpandedKeys.value)) {
				// 默认展开2级
				treeData.value.forEach((item) => {
					// 因为0的顶级
					if (item.parentId === 0) {
						defaultExpandedKeys.value.push(item.id)
						// 取到下级ID
						if (item.children) {
							item.children.forEach((items) => {
								defaultExpandedKeys.value.push(items.id)
							})
						}
					}
				})
			}
		}
	})
	// 列表选择配置
	const options = reactive({
		alert: {
			show: true, //显示选择多少个
			clear: () => {
				selectedRowKeys.value = ref([])
			}
		},
		rowSelection: {
			onChange: (selectedRowKey, selectedRows) => {
				selectedRowKeys.value = selectedRowKey
			}
		}
	})
	// 点击树查询
	const treeSelect = (selectedKeys) => {
		if (selectedKeys.length > 0) {
			searchFormState.value.orgId = selectedKeys.toString()
		} else {
			delete searchFormState.value.orgId
		}
		table.value.refresh(true)
	}
	// 修改状态
	const editStatus = (record) => {
		loading.value = true
		if (record.userStatus === 'ENABLE') {
			userApi
				.userDisableUser(record)
				.then(() => {
					table.value.refresh()
				})
				.finally(() => {
					loading.value = false
				})
		} else {
			userApi
				.userEnableUser(record)
				.then(() => {
					table.value.refresh()
				})
				.finally(() => {
					loading.value = false
				})
		}
	}
	// 删除用户
	const removeUser = (record) => {
		let params = [
			{
				id: record.id
			}
		]
		userApi.userDelete(params).then(() => {
			table.value.refresh()
		})
	}
	// 批量删除用户
	const removeBatchUser = (params, callback) => {
		userApi
			.userDelete(params)
			.then(() => {})
			.finally(() => {
				table.value.clearRefreshSelected()
				callback() //调用组件中的回调方法
			})
	}
	// 打开角色选择器
	const selectRole = (record) => {
		selectedRecord.value = record
		// 查询到已有角色，并转为ids的格式，给角色选择器
		const param = {
			id: record.id
		}
		userApi.userOwnRole(param).then((data) => {
			RoleSelectorPlusRef.value.showRolePlusModal(data)
		})
	}
	// 角色选择回调
	const roleBack = (value) => {
		let params = {
			id: selectedRecord.value.id,
			roleIdList: []
		}
		if (value.length > 0) {
			value.forEach((item) => {
				params.roleIdList.push(item.id)
			})
		}
		userApi.grantRole(params).then(() => {})
	}
	// 重置用户密码
	const resetPassword = (record) => {
		userApi.userResetPassword(record).then(() => {})
	}

	// 打开导入界面
	const openImport = (record) => {
		nextTick(() => {
			importRef.value.importSteps(record)
		})
	}
	// 导出数据
	const dataExportUser = (callback) => {
		userApi
			.userExport(searchFormState.value)
			.then((data) => {
				callback(data)
			})
			.catch(() => {
				callback(null)
			})
	}
	// 传递设计器需要的API
	const selectorApiFunction = {
		orgTreeApi: (param) => {
			return userApi.userOrgTreeSelector(param).then((data) => {
				return Promise.resolve(data)
			})
		},
		rolePageApi: (param) => {
			return userApi.userRoleSelector(param).then((data) => {
				return Promise.resolve(data)
			})
		},
		checkedRoleListApi: (param) => {
			return userCenterApi.userCenterGetRoleListByIdList(param).then((data) => {
				return Promise.resolve(data)
			})
		}
	}
</script>

<style scoped>
	.cardImp {
		margin-right: 10px;
	}

	.ant-form-item {
		margin-bottom: 0 !important;
	}

	.primaryAdd {
		margin-right: 10px;
	}

	.snowy-table-avatar {
		margin-top: -10px;
		margin-bottom: -10px;
	}

	.buttom-left {
		margin-left: 8px;
	}
</style>
